<template>
  <div class="profile-container">
    <div class="profile-content">
      <el-card class="profile-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <h3>个人信息</h3>
            <el-button type="primary" round @click="handleEdit">
              <el-icon><Edit /></el-icon>
              编辑资料
            </el-button>
          </div>
        </template>
        <div class="profile-info">
          <div class="avatar-wrapper">
            <el-avatar :size="100" :src="userInfo?.avatar || defaultAvatar" />
            <p class="role-tag">{{ getRoleName(userInfo?.roleCode) }}</p>
          </div>
          <div class="info-details">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="用户名">{{ userInfo?.username }}</el-descriptions-item>
              <el-descriptions-item label="昵称">{{ userInfo?.nickname }}</el-descriptions-item>
              <el-descriptions-item label="邮箱">{{ userInfo?.email }}</el-descriptions-item>
              <el-descriptions-item label="手机号">{{ userInfo?.phone || '未设置' }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{ getGenderText(userInfo?.gender) }}</el-descriptions-item>
              <el-descriptions-item label="最后登录时间">{{ formatDateTime(userInfo?.lastLoginTime) }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </div>
        <div class="profile-action">
          <el-button type="primary" round @click="showPasswordDialog">
            <el-icon><Key /></el-icon>
            修改密码
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 编辑个人信息对话框 -->
    <el-dialog
      v-model="editDialog.visible"
      title="编辑个人信息"
      width="500px"
      destroy-on-close
      center
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="100px"
        status-icon
      >
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="editForm.nickname" placeholder="请输入昵称" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="editForm.gender">
            <el-radio :label="0">未知</el-radio>
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button round @click="editDialog.visible = false">取 消</el-button>
          <el-button type="primary" round @click="submitEditForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialog.visible"
      title="修改密码"
      width="500px"
      destroy-on-close
      center
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordFormRules"
        label-width="100px"
        status-icon
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入原密码" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button round @click="passwordDialog.visible = false">取 消</el-button>
          <el-button type="primary" round @click="submitPasswordForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Edit, Key } from '@element-plus/icons-vue'
import { getUserInfo } from '@/api/user'
import { updateUserProfile, updatePassword } from '@/api/user' // 需要新增这两个API方法

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

const router = useRouter()
const userInfo = ref(null)

// 编辑表单
const editDialog = reactive({
  visible: false
})

const editFormRef = ref(null)
const editForm = reactive({
  id: undefined,
  nickname: '',
  email: '',
  phone: '',
  gender: 0
})

const editFormRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { max: 50, message: '昵称长度不能超过50个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 密码表单
const passwordDialog = reactive({
  visible: false
})

const passwordFormRef = ref(null)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const passwordFormRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6-20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 获取角色名称
const getRoleName = (roleCode) => {
  switch (roleCode) {
    case 'ADMIN':
      return '管理员'
    case 'INITIATOR':
      return '发起人'
    case 'CONTESTANT':
      return '参赛者'
    default:
      return roleCode
  }
}

// 获取性别文本
const getGenderText = (gender) => {
  switch (gender) {
    case 0:
      return '未知'
    case 1:
      return '男'
    case 2:
      return '女'
    default:
      return '未知'
  }
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '未登录'
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(/\//g, '-')
}

// 显示编辑表单对话框
const handleEdit = () => {
  if (!userInfo.value) return
  
  // 填充表单数据
  editForm.id = userInfo.value.id
  editForm.nickname = userInfo.value.nickname
  editForm.email = userInfo.value.email
  editForm.phone = userInfo.value.phone || ''
  editForm.gender = userInfo.value.gender
  
  editDialog.visible = true
}

// 提交编辑表单
const submitEditForm = async () => {
  if (!editFormRef.value) return
  
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await updateUserProfile(editForm)
        ElMessage.success('个人信息更新成功')
        editDialog.visible = false
        
        // 刷新用户信息
        fetchUserInfo()
      } catch (error) {
        console.error('更新个人信息失败', error)
      }
    }
  })
}

// 显示修改密码对话框
const showPasswordDialog = () => {
  passwordDialog.visible = true
}

// 提交修改密码表单
const submitPasswordForm = async () => {
  if (!passwordFormRef.value) return
  
  passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await updatePassword({
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        })
        
        ElMessage.success('密码修改成功，请重新登录')
        passwordDialog.visible = false
        
        // 清除登录状态，返回登录页
        setTimeout(() => {
          localStorage.removeItem('token')
          localStorage.removeItem('userInfo')
          router.push('/login')
        }, 1500)
      } catch (error) {
        console.error('修改密码失败', error)
      }
    }
  })
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    // 先尝试从本地存储获取
    const storedUserInfo = localStorage.getItem('userInfo')
    if (storedUserInfo) {
      userInfo.value = JSON.parse(storedUserInfo)
    }
    
    // 然后再请求最新的用户信息
    const res = await getUserInfo()
    userInfo.value = res.data
    localStorage.setItem('userInfo', JSON.stringify(res.data))
  } catch (error) {
    console.error('获取用户信息失败', error)
  }
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style lang="scss" scoped>
.profile-container {
  .profile-content {
    max-width: 800px;
    margin: 0 auto;
    
    .profile-card {
      border-radius: 8px;
      overflow: hidden;
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        h3 {
          margin: 0;
          font-size: 18px;
          font-weight: 600;
          color: #303133;
        }
      }
      
      .profile-info {
        display: flex;
        padding: 20px 0;
        
        @media (max-width: 768px) {
          flex-direction: column;
          align-items: center;
        }
        
        .avatar-wrapper {
          display: flex;
          flex-direction: column;
          align-items: center;
          padding: 0 30px;
          
          .el-avatar {
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            border: 4px solid #fff;
          }
          
          .role-tag {
            margin-top: 15px;
            padding: 4px 12px;
            background-color: #ecf5ff;
            border-radius: 16px;
            color: #409eff;
            font-size: 12px;
            font-weight: 600;
          }
        }
        
        .info-details {
          flex: 1;
        }
      }
      
      .profile-action {
        margin-top: 20px;
        display: flex;
        justify-content: center;
      }
    }
  }
}

:deep(.el-descriptions__label) {
  width: 100px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-button--danger) {
  --el-button-hover-bg-color: #f56c6c;
  --el-button-hover-border-color: #f56c6c;
  --el-button-hover-text-color: #fff;
  
  &:hover {
    background-color: var(--el-button-hover-bg-color);
    border-color: var(--el-button-hover-border-color);
    color: var(--el-button-hover-text-color);
  }
}

:deep(.el-button--primary) {
  --el-button-hover-bg-color: #409eff;
  --el-button-hover-border-color: #409eff;
  --el-button-hover-text-color: #fff;
  
  &:hover {
    background-color: var(--el-button-hover-bg-color);
    border-color: var(--el-button-hover-border-color);
    color: var(--el-button-hover-text-color);
  }
}
</style> 